package com.arrogames.tmx {
	import com.arrogames.rgblabyrinth.AssetManager;
	import com.arrogames.rgblabyrinth.game.graphics.GridBorderLayer;
	import com.arrogames.rgblabyrinth.game.graphics.TiledLayer;
	import com.arrogames.rgblabyrinth.game.graphics.TmxTile;
	import net.pixelpracht.tmx.TMXOrientation;
	
	import flash.display.Bitmap;
	import flash.geom.Point;
	
	import net.pixelpracht.tmx.TmxLayer;
	import net.pixelpracht.tmx.TmxMap;
	import net.pixelpracht.tmx.TmxTileOffset;
	import net.pixelpracht.tmx.TmxTileSet;
	
	import starling.display.Sprite;
	import starling.textures.TextureAtlas;
	
	public class StarlingMap extends TmxMap {
		
		private var _textureAtlas:TextureAtlas;
		private var _tiledLayers:Vector.<Sprite> = new Vector.<Sprite>();
		
		public function StarlingMap(source:XML) {
			super(source);
		}

		public function createTiledLayers():void {
			for (var layer:String in layers) {
				var mapLayer:TmxLayer = getLayer(layer);
				createTileLayer(mapLayer);
			}
		}
		
		public function addTileSetTexture(tileSetName:String, embeddedImage:Class):void {
			var tileSet:TmxTileSet = getTileSet(tileSetName);
			var bmp:Bitmap = new embeddedImage() as Bitmap;
			tileSet.associatedImage = bmp.bitmapData;
			AssetManager.instance.addTextureAtlas(tileSetName, tileSet.textureAtlas);
		}
		
		private function createTileLayer(mapLayer:TmxLayer):void {
			var rows:Array = mapLayer.tileGIDs;
			var tileLayer:TiledLayer = new TiledLayer(mapLayer);
			var tile:TmxTile;
			
			for (var row:int = 0; row < rows.length; row++) {
				var columns:Array = rows[row] as Array;
				for (var column:int = 0; column < columns.length; column++) {
					var GID:int = columns[column];
					var tileSet:TmxTileSet = getGidOwner(GID);
					if (GID > 0) {
						tile = createTile(GID, tileSet, row, column);
						tileLayer.addTile(tile);
					}
				}
			}
			_tiledLayers.push(tileLayer);
		}
		
		private function createTile(gid:int, tileSet:TmxTileSet, row:int, column:int) : TmxTile {
			var tile:TmxTile = new TmxTile(gid, AssetManager.instance.getTexture(gid.toString()));
			
			var tileOffset:TmxTileOffset = tileSet.tileOffset;
			var screen:Point = CoordinateUtil.isometricToScreen(column, row, this.tileWidth, this.tileHeight);
			tile.x = screen.x - tileOffset.x - this.tileWidth/2;
			tile.y = screen.y - tileOffset.y;
			return tile;
		}
		
		public function get tiledLayers():Vector.<Sprite>{
			return _tiledLayers;
		}
	}
}